<template>
  <login-lay>
    <div class="sign-in">
      <div class="logo">
        <img src="../../assets/image/logo_blue.png" />
      </div>
      <div class="sign-in__title">忘记密码</div>
      <div class="sign-in__info">请输入您注册时的手机号进行验证</div>
      <el-form
        ref="form"
        class="sign-in__form"
        label-position="top"
        :model="form"
        :rules="rules"
      >
        <el-form-item prop="mobile" class="mb-30">
          <div
            class="input-phone-004 w-full sign-in__iput"
            style="border-radius: 10px; overflow: hidden"
          >
            <div class="input-phone-004__inner">
              <el-input
                v-model="form.mobile"
                placeholder="请输入手机号"
                style="font-size: 20px"
                type="number"
              >
                <template #prepend>
                  <div
                    class="select-004 select-004--large"
                    style="width: 116px"
                  >
                    <el-select v-model="form.areaNumber">
                      <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                </template>
              </el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="code" class="mb-30">
          <div
            class="input-password-004 input-password-004--clearable input-password-004--show-password w-full sign-in__iput"
            style="border-radius: 10px; overflow: hidden"
          >
            <el-input
              v-model="form.code"
              placeholder="请输入验证码"
              type="test"
            ></el-input>
            <span
              class="eye_potion"
              style="
                width: 120px;
                text-align: center;
                font-size: 16px;
                color: #6b1ce9;
                font-weight: bold;
              "
              :disabled="isGetphone"
              @click="sendPhoneCode()"
            >
              {{ phoneCode }}
            </span>
          </div>
        </el-form-item>
        <el-form-item prop="password">
          <div
            class="input-password-004 input-password-004--clearable input-password-004--show-password w-full sign-in__iput"
            style="border-radius: 10px; overflow: hidden"
          >
            <el-input
              v-model="form.password"
              placeholder="请输入登录密码"
              :type="passwordType"
            ></el-input>
            <span
              :class="
                passwordType == 'text'
                  ? 'eye_potion icon_eye_1'
                  : 'eye_potion icon_eye'
              "
              @click="changePasswordType"
            ></span>
          </div>
          <div class="text-align-right w-full mt-14">
            <RouterLink to="/login">
              <div
                class="d-inline-block lh-22 fs-16 c-link-blue cursor-pointer"
              >
                去登录
              </div>
            </RouterLink>
          </div>
        </el-form-item>
        <el-button
          class="button-004 button-004--primary button-004--large w-full mt-100 h-60 fs-16 border-radius-8"
          :disabled="submitDisabled"
          :loading="loading"
          style="background-color: #6b1ce9"
          @click="handleSubmit"
        >
          确认
        </el-button>
      </el-form>
    </div>
  </login-lay>
</template>

<script>
  import LoginLay from '@/vab/layouts/LoginLay.vue'
  import { mapActions, mapGetters } from 'vuex'
  import { translateTitle } from '@/utils/i18n'
  import { isPassword, isPhone } from '@/utils/validate'
  import { getCode } from '@/api/sms'
  import { resetpwd } from '@/api/user'

  export default {
    name: 'ForgetPassword',
    components: {
      LoginLay,
    },
    directives: {
      focus: {
        inserted(el) {
          el.querySelector('input').focus()
        },
      },
    },
    beforeRouteLeave(to, from, next) {
      clearInterval(this.timer)
      next()
    },
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!isPhone(value))
          callback(new Error(this.translateTitle('手机号格式不对')))
        else callback()
      }
      const validatePassword = (rule, value, callback) => {
        if (!isPassword(value))
          callback(new Error(this.translateTitle('密码不能少于6位')))
        else callback()
      }
      return {
        form: {
          mobile: '',
          password: '',
          code: '',
          fingerprint: '',
          areaNumber: '+86',
        },
        rules: {
          mobile: [
            {
              required: true,
              trigger: 'blur',
              validator: validateUsername,
            },
          ],
          password: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePassword,
            },
          ],
          code: [
            {
              required: true,
              trigger: 'blur',
              message: '验证码不能空',
            },
          ],
        },
        isGetphone: false,
        getPhoneIntval: null,
        phoneCode: '获取验证码',
        submitDisabled: false,
        loading: false,
        passwordType: 'password',
        redirect: undefined,
        timer: 0,
        codeUrl: 'https://www.oschina.net/action/user/captcha',
        previewText: '',
        options: [
          {
            value: '+86',
            label: '+86',
          },
        ],
      }
    },
    computed: {
      ...mapGetters({
        title: 'settings/title',
      }),
    },
    watch: {
      $route: {
        handler(route) {
          this.redirect = (route.query && route.query.redirect) || '/'
        },
        immediate: true,
      },
    },
    mounted() {
      /*this.form.mobile = '18659350916'
      this.form.password = '123456aA'
      this.form.fingerprint = '1'*/
      // 为了演示效果，会在官网演示页自动登录到首页，正式开发可删除
      // if (
      //   document.domain === 'vue-admin-beautiful.com' ||
      //   document.domain === 'chu1204505056.gitee.io'
      // ) {
      //   this.previewText = '（演示地址验证码可不填）'
      //   this.timer = setTimeout(() => {
      //     this.handleLogin()
      //   }, 5000)
      // }
    },
    methods: {
      ...mapActions({
        login: 'user/login',
      }),
      translateTitle,
      handlePassword() {
        this.passwordType === 'password'
          ? (this.passwordType = '')
          : (this.passwordType = 'password')
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleRoute() {
        return this.redirect === '/404' || this.redirect === '/403'
          ? '/'
          : this.redirect
      },
      handleSubmit() {
        this.$refs.form.validate(async (valid) => {
          if (valid){
            let data = {
              mobile: this.form.mobile,
              captcha: this.form.code,
              newpassword: this.form.password
            }
            const { code, msg } = await resetpwd(data)
            if (code === 1) {
              this.$baseMessage(msg, 'success')
              this.$router.push('/login')
            } else {
              this.isGetphone = false
              this.$baseMessage(msg, 'error')
            }
          }
            /*try {
              this.loading = true
              await this.login(this.form).catch(() => {})
              await this.$router.push(this.handleRoute())
            } finally {
              this.loading = false
            }*/
        })
      },
      sendPhoneCode () {
        this.$refs.form.validateField(['mobile'], async (error) => {
          if (!error) {
            if (!this.isGetphone) {
              let data = {
                mobile: this.form.mobile,
                event: "resetpwd"
              }
              this.isGetphone = true
              const { code, msg } = await getCode(data)
              if (code === 1) {
                this.$baseMessage(msg, 'success')
                this.getPhoneCode()
              } else {
                this.isGetphone = false
                this.$baseMessage(msg, 'error')
              }
            } else {
              return
            }
          } else {
            this.$message.error('请输入正确的手机号')
          }
        })
      },

      getPhoneCode () {
        let n = 60
        this.getPhoneIntval = setInterval(() => {
          if (n > 0) {
            n--
            this.phoneCode = '已发送(' + n + 's)'
          } else {
            this.getPhoneIntval = null
            clearInterval(this.getPhoneIntval)
            this.phoneCode = '获取验证码'
            this.isGetphone = false
          }
        }, 1000)
      },

      changeCode() {
        this.codeUrl = `https://www.oschina.net/action/user/captcha?timestamp=${new Date().getTime()}`
      },

      changePasswordType() {
        this.passwordType =
          this.passwordType == 'password' ? 'text' : 'password'
      },
    },
  }
</script>

<style lang="scss" scoped>
  .eye_potion {
    position: absolute;
    width: 32px;
    height: 32px;
    right: 20px;
    top: 16px;
    cursor: pointer;
  }
  .icon_eye_1 {
    background-image: url('../../assets/image/eye_1.png');
    background-position: 1px;
    background-size: 100%;
  }
  .icon_eye {
    background-image: url('../../assets/image/eye.png');
    background-position: 1px;
    background-size: 100%;
  }
  .sign-in {
    position: relative;
    width: 100%;
    margin-top: 50px;
    .logo {
      width: 156px;
      height: 46px;
      position: absolute;
      left: 50%;
      top: -100px;
      margin-left: -78px;
      img {
        width: 100%;
      }
    }
    .sign-in__title {
      font-size: 30px;
      font-weight: 600;
      line-height: 53px;
      color: #000000;
    }
    .sign-in__info {
      margin-top: 4px;
      font-size: 16px;
      line-height: 28px;
      color: #666666;
    }
    .sign-in__form {
      margin-top: 60px;
      .sign-in__iput {
        height: 60px;
      }
    }
    .input-004--normal {
      height: 60px !important;
    }
    .el-form-item {
    }
  }

  ::v-deep(.el-input__wrapper) {
    background-color: unset !important;
    box-shadow: unset !important;
  }
  ::v-deep(.el-select) {
    &.el-select--disabled {
      border-style: none;
    }
  }

  ::v-deep(.el-form-item__error) {
    height: 0;
    font-size: 15px;
    line-height: 20px;
    color: var(--color-red);
    transition: height 0.3s;
  }
  ::v-deep {
    .el-select__wrapper {
      height: 100%;
    }
    .el-select__wrapper.is-disabled {
      background: none;
      box-shadow: none;
    }
    .select-004--large .el-select {
      background: none;
      border: none;
    }
    .input-004 {
      background: #f3f4f5;
    }
    .el-input-group__prepend {
      border: none;
      box-shadow: none;
    }
    .el-input-group--prepend
      .el-input-group__prepend
      .el-select
      .el-select__wrapper {
      box-shadow: none;
      background: #f3f4f5;
    }
    .select-004--large .el-select {
      margin: 0;
    }
    .el-select__wrapper {
      font-size: 22px;
    }
    .input-phone-004 .el-select .el-input__icon {
      display: none;
    }
    .el-input__inner {
      height: 60px;
      font-size: 20px;
      color: #000;
      background: #f3f4f5;
      border: none;
    }
  }
</style>
